package com.studynotes.dev.tech.common.utils;

import cn.hutool.core.util.PrimitiveArrayUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.extra.spring.SpringUtil;
import com.studynotes.dev.tech.common.enums.CryptoModelEnum;
import com.studynotes.dev.tech.config.properties.CryptoFieldSettingProperties;

import java.nio.charset.StandardCharsets;

/**
 * @author Liu XiaoJun
 * @description: 字段加密工具类
 * @date 2025-11-07 15:05:54
 */
public class FieldCryptoUtil {

    private static final CryptoFieldSettingProperties cryptoFieldSettingProperties;

    static {
        cryptoFieldSettingProperties = SpringUtil.getBean(CryptoFieldSettingProperties.class);
    }

    private FieldCryptoUtil() {
        throw new IllegalStateException("Utility class");
    }

    public static String encrypt(String rawValue) {

        if (CryptoModelEnum.AES.name().equals(cryptoFieldSettingProperties.getModel())) {
            AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, cryptoFieldSettingProperties.getKey().getBytes(StandardCharsets.UTF_8), PrimitiveArrayUtil.sub(cryptoFieldSettingProperties.getIv(), 0, 16));
            return aes.encryptBase64(rawValue, StandardCharsets.UTF_8);
        }
        DES des = new DES(Mode.CBC, Padding.PKCS5Padding, cryptoFieldSettingProperties.getKey().getBytes(StandardCharsets.UTF_8), PrimitiveArrayUtil.sub(cryptoFieldSettingProperties.getIv(), 5, 13));
        return des.encryptBase64(rawValue, StandardCharsets.UTF_8);
    }

    public static String decrypt(String encrypted) {
        if (CryptoModelEnum.AES.name().equals(cryptoFieldSettingProperties.getModel())) {
            AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, cryptoFieldSettingProperties.getKey().getBytes(StandardCharsets.UTF_8), PrimitiveArrayUtil.sub(cryptoFieldSettingProperties.getIv(), 0, 16));
            return aes.decryptStr(encrypted);
        }
        DES des = new DES(Mode.CBC, Padding.PKCS5Padding, cryptoFieldSettingProperties.getKey().getBytes(StandardCharsets.UTF_8), PrimitiveArrayUtil.sub(cryptoFieldSettingProperties.getIv(), 5, 13));
        return des.decryptStr(encrypted);
    }
}
